package day11.HomeWork;

import java.util.Scanner;
import java.util.concurrent.locks.ReentrantLock;

//b.使用公平锁ReentrantLock实现一个线程安全的计数器，
// 多个线程同时递增计数，最后输出正确结果
public class Demo2 {
    ReentrantLock lock = new ReentrantLock(true);
    static Scanner sc = new Scanner(System.in);
    static int num = sc.nextInt();
    static int n = 0;

    public void count() {
        try {
            String name = Thread.currentThread().getName();
            lock.lock();
            if (n < num) {
                n++;
                System.out.println(name + " " + n);
            }
            if (n >= num) {
                return;
            }
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Demo2 d = new Demo2();
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                for (int j = 0; j < num; j++) {
                    d.count();
                }
            }, "线程" + i).start();
        }
    }
}
